﻿using System;
using System.Linq;
using System.Web.UI;
using Pentia.Linq;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Data.Linq;
using Sitecore.Data.Query;

namespace Sitecore.Data.Linq.Test
{
  public partial class TestPage : Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      Response.Output.NewLine = "<br/>";
      PrintQueryTree("/sitecore/content/home[@@name='sitecore']");

      //TODO: This needs to be registered in the Global.asax
      SitecoreEntityRegistration.RegisterClasses();

      // Create an item context from the 
      Database database = Factory.GetDatabase("master");
      Item queryItem = database.SelectSingleItem("/sitecore/content");
      
      var ctx = new SitecoreContext<ISampleItem>(queryItem, Axis.Children)
                  {Log = Response.Output};
      try
      {
        var items = from i in ctx 
                    where i.Name == "Home"
                    select i;
        foreach (ISampleItem item in items)
        {
          Response.Output.WriteLine(item.Name);
        }
      }
      catch (Exception ex)
      {
        while (ex != null)
        {
          Response.Write(String.Format("{0}<br/>{1}", ex.Message, ex.StackTrace.Replace("\n", "<br/>")));
          ex = ex.InnerException;
        }
      }
    }

    /// <summary>
    /// Sitecore Query syntax tester
    /// </summary>
    /// <param name="query"></param>
    private void PrintQueryTree(string query)
    {
      Response.Output.WriteLine("-TEST---------------------");
      Response.Output.WriteLine(query);
      Opcode code = QueryParser.Parse(query);
      code.Print(new HtmlTextWriter(Response.Output));
      Response.Output.WriteLine("--------------------------");

    }
  }
}